<?php

class UserController extends Vnf_Controller_Action
{
	function init() {
            parent::init();
//        if(count($config)>0){
//            $this->view->title= $title = $config->title;
//            $this->view->description= $title = $config->description;
//            $this->view->keywords= $title = $config->keywords;
//        }
//        else{
//           $this->view->title  = $conf->default->tilte;
//           $this->view->description  = $conf->default->description;
//           $this->view->keywords  = $conf->default->keywords;
//        }
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
    }
    function indexAction() {
        $this->_redirect('user/listuser');
    }
    
    function leftAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        @$this->view->access = $defaultNamespace->access;
    }
    
    function accountfunctionAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $user = $defaultNamespace->user;
        
        @$this->view->username = $user['Email'];
    }
    public function registerAction(){
         $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
        $currentPage = $this->view->currentPage;
        
        
    }

    public function activeAction(){
         $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
    }

    public function prepareData() {
        $params = $this->getParams();
        //$currentPageID = 0;
        $category = new Category();
        /*
        $this->view->allFullFriendlyUrl = $allFullFriendlyUrl = $category->getAllFullFriendlyUrl();

        //echo "-----" . stristr($_SERVER['REDIRECT_URL'], BASE_URL);
        if(stristr($_SERVER['REDIRECT_URL'], BASE_URL)) {
            $friendlyUrl = substr($_SERVER['REDIRECT_URL'], strlen(BASE_URL));
            $allFullFriendlyUrl = $this->view->allFullFriendlyUrl;

            //print_r($allFullFriendlyUrl);
            if (isset($allFullFriendlyUrl[$friendlyUrl])) {
                $currentPageID = $allFullFriendlyUrl[$friendlyUrl];
                $this->view->currentPageID = $currentPageID;
            }
        }

        */
        $currentPageID = $this->getParam('pid', $this->view->currentPageID);
        $id = $this->getParam('id', 0); // item id

        // get default content if has not page transfer
        $showDefaultPage = false;
        $getSubPage = false;
        if ($currentPageID <= 0) {
            $root = $category->getRoot();
            $currentPageID = $root->category_id;
            if ($id == 0) $getSubPage = true; // item id

            $this->view->showDefaultPage = $showDefaultPage = true;
        }
        $this->view->currentPageID =  $currentPageID;


        $allCategory = $category->getCacheOfCategory();

        $this->view->allCategory = $allCategory;

        $currentPage = $allCategory[$currentPageID];
        $categoryPath = $currentPage['all_parent']!=""?$currentPage['all_parent'].",".$currentPageID : $currentPageID;

        $this->view->categoryPath = explode(',', $categoryPath);
        if (!is_array($this->view->categoryPath)) {
            $this->view->categoryPath = array();
        }
        $this->view->currentPage = $currentPage;

//        print_r($currentPage);

        $childPage = array();
        @$childPage = $currentPage['children'];
        $this->view->currentChild = $childPage;

        if ($getSubPage) {
            if (isset($childPage[0])) {
                $this->view->currentPageID =  $currentPageID = $childPage[0];
                $this->view->currentPage = $allCategory[$currentPageID];
            }
        }

        $paramsTransfer = $params;
        unset($paramsTransfer['loginform']);
        if (isset($paramsTransfer['lastparams'])) {
            $this->view->paramsEncode = $paramsTransfer['lastparams'];
            unset($paramsTransfer['lastparams']);
        } else {
            $this->view->paramsEncode = Zend_Json::encode($paramsTransfer);
        }


    }

    public function forgotpasswordAction(){
         $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
        $currentPage = $this->view->currentPage;
        $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
        $conf = Vnf::getConfigs('conf');
        @$registermail = $conf->registermail?$conf->registermail:'info@'.$domain;
        $flag = true;
        $this->view->flag =$flag ;
        if($this->_request->isPost()){
               
              //$user = new User();
              
              $user = new Customer();
              
              $email = $this->getParam("email");
              $where = "Email ='".$email."'";
              $row = $user->fetchRow($where);
              //print_r($row['username']);die;
              if($row){
                    $this->view->flag =$flag ;
                    echo $random = rand(1, 99999999999);
                    $row= $row->toArray();
                    $data = array(
                        'password' => $random
                    );
                    $where = "CustomerNo = '" . $row['CustomerNo'] . "'";
                    $user->update($data,$where);
                    $mail = new Zend_Mail("utf-8");
                    $mail->setBodyHtml("Email: ".$row['Email']. "</br> New password: ".$random)
                        ->setFrom($registermail)
                        ->addTo($email)
                        ->setSubject("Reset Password")
                        ->send();
                    $this->view->error =$error = "New password has sent to your email.";

                }
                else {
                    $flag = false;
                    $this->view->flag =$flag ;
                    $this->view->error =$error = "Wrong email. Please check again.";
                }

             }
    }
    
    public function listuserinnerAction(){
        $currentPage = $this->view->currentPage;
        $objItem = new User();
            $status = (int)$this->getParam('status',1);
            
            $seeking = $this->getParam('seeking', null);
            $for = $this->getParam('for', null);
            $agefrom = (int)$this->getParam('agefrom', 0);
            $ageto = (int)$this->getParam('ageto', 0);
            $username = $this->getParam('username', null);
            $photo = $this->getParam('photo', 'off');
            
            $where = "thistable.status = " . $status;
            
            $tmp_where = "";
            //if ($seeking) { $tmp_where .= " AND thistable.gender = '$seeking'";}
            if ($seeking) { $tmp_where .= " AND thistable.iam = '$seeking'";}
            if ($for) { $tmp_where .= " AND thistable.for = '$for'";}
            if ($username) { $tmp_where .= " AND thistable.username = '$username'";}
            if ($photo == 'on') { $tmp_where .= " AND thistable.main_image != ''";}
            if ($agefrom > 0) {
                $givendate = date('Y-12-31', time());
                $query_date = $this->add_date($givendate, 0, 0, -($agefrom), 'Y-m-d');
                $tmp_where .= " AND thistable.birtday <= '$query_date'";
            }
            if ($ageto > 0) {
                $givendate = date('Y-01-01', time());
                $query_date = $this->add_date($givendate, 0, 0, - ($ageto), 'Y-m-d');
                $tmp_where .= " AND thistable.birtday >= '$query_date'";
            }
            
            $where .= $tmp_where;
            $totalRecords = $objItem->getTotalRecords($where);
			//print_r($totalRecords);die;
            $currentPaging = (int) $this->getParam('page', 1);

			//echo $currentPaging;
			//echo $currentPaging;
            $currentPaging--;

            $numberPageView = 5;
            $recordsPerPage = (int) $this->getParam('records', RECORDS_PER_PAGE);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:RECORDS_PER_PAGE;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;
			//echo $currentPage.'aa';
			//echo $currentPaging;
			//print_r($totalRecords);

			$link =  BASE_PATH . '/' . CURR_APP . "/user/listuser?status=$status"; //truyen param o day
			$tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
//            $order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, $link, $numberPageView, $tagID, $class,'false');

            $pk = $objItem->getPrimaryKey();
            //$where = "node.status =".$status;
            //$where .= $tmp_where;
            $order = "$pk DESC";
            $items = $objItem->getAllRecords($where, $order, $recordsPerPage, $recordsPerPage * $currentPaging);
			//print_r($items);
            //echo $recordsPerPage * $currentPaging;
            // get all items in current page and sub page
//            $items = $objItem->getRecords("$where", "item_id DESC");

           $this->view->allItems = $items;
    }
    
    public function listuserAction(){
          $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
    }
    public function detailuserAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    public function detailuserinnerAction(){
        $currentPage = $this->view->currentPage;

        $id = (int)$this->getParam('id', 0);
        $user = new User();
        $where = 'category_id ='.$id ;
        $row = $user->fetchAll($where);
        $this->view->row =$row;

        /*
        $image = new Image();
        if ($id > 0) {
            $where = 'category_id =' . $id;
            $rows = $image->getRecords($where, 'image_id Desc');
            $this->view->rows = $rows ;
        }
        */
    }
    public function editprofileAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        $currentPage = $this->view->currentPage;
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
    }
    
    public function editdetailAction(){
        
         $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $country = new Country();
        $rowcountry = $country->fetchAll();
        $this->view->rowcountry = $rowcountry;

        if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
             $this->view->member = $meber =$defaultNamespace->user;
             /*
             echo "<pre>";
             print_r($meber);
             echo "</pre>";
             */
            $customer_id = $meber['CustomerNo'];
            $this->view->username = $meber['Email'];
            $this->view->lastname = $meber['LastName'];
            //$this->view->firstname = $meber['Firstname'];
            //$this->view->stress = $meber['Stress'];
            //$user = new Customer();
            //print_r($row);die;
            
            $user = new Customer();
            $customer = $user->getRecords("thistable.CustomerNo = '$customer_id'", null, 1 ,0);
            if (count($customer) > 0) {
                //$this->view->row = $meber;
                
                $firstname = $this->getParam('firstname','');
                $lastname = $this->getParam('lastname','');
                $email = $this->getParam('email','');
                $company = $this->getParam('company','');
                $Street = $this->getParam('Street','');
                $Street2 = $this->getParam('Street2','');
                $city = $this->getParam('city','');
                $state = $this->getParam('state','');
                $zip = $this->getParam('zip','');
                $country = $this->getParam('country','');
                
                $phone = $this->getParam('Phone','');
                $phone2 = $this->getParam('Phone2','');
                $fax = $this->getParam('Fax','');
                
                $CreditCard = $this->getParam('CreditCard','');
                $ExpDate = $this->getParam('ExpDate','');
                $CCV = $this->getParam('CCV','');
                
                $submit = $this->getParam('submit','');
                if($submit != ''){
                    
                    $data = array(
                        'Lastname' => $lastname,
                        'Firstname' => $firstname,
                        //'Email' => $email,
                        'Company' => $company,
                        'Street' => $Street,
                        'Street2' => $Street2,
                        'City' => $city,
                        'State'=>$state,
                        'Zip' => $zip,
                        'Country' => $country,
                        'Phone'=>$phone,
                        'Phone2' => $phone2,
                        'Fax' => $fax,
                        'CreditCard' => $CreditCard,
                        'ExpDate' => $ExpDate,
                        'CCV' => $CCV,
                    );
                    
                    $whereid = 'CustomerNo = ' .$customer_id;
                    $user->update( $data,$whereid);
                    
                    // update session after update data
                    $user = $user->getRecords("thistable.CustomerNo = '$customer_id'", null, 1 ,0);
                    if (count($user) > 0)
                    {
                        $defaultNamespace = new Zend_Session_Namespace('Default');
                        $defaultNamespace->user = $user[0];
                    }
                    
                    $this->_redirect('user/viewprofile');
                }
                //print_r($this->view->row);die;
            }
                


            
                
                //print_r($row);die;
            
        }
    }
    
    public function editemailcustomerAction(){
        $this->prepareData();
    }
    
    public function editemailcustomerinnerAction(){
        
         $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
             $this->view->member = $meber =$defaultNamespace->user;
             $email = $this->getParam('newemail','');
            $customer_id = $meber['CustomerNo'];
            $this->view->user = $username = $meber;
            $user = new Customer();
            $customer = $user->getRecords("thistable.CustomerNo = '$customer_id'", null, 1 ,0);
            $customerorther = $user->getRecords("thistable.Email = '$email'", null, 1 ,0);
            if (count($customer) > 0) {
                
                    if($this->getParam('submitEditEmail', '') != ''){
                        if((count($customerorther) == 0))
                        {
                            $data = array(
                                'Email' => $email
                            );
                            
                            $whereid = 'CustomerNo = ' .$customer_id;
                            $user->update( $data,$whereid);
                            
                            $user = $user->getRecords("thistable.CustomerNo = '$customer_id'", null, 1 ,0);
                            if (count($user) > 0)
                            {
                                $defaultNamespace = new Zend_Session_Namespace('Default');
                                $defaultNamespace->user = $user[0];
                                $this->view->member = $user[0];
                            }
                            echo $this->view->msg =  "Change email successfull!";
                            //$this->_redirect('user/viewprofile');
                        } else {
                            echo $this->view->msg =  "Please change another email! Email already exists.";
                        }
                        
                    }
                    
                
                //print_r($this->view->row);die;
            }
        }
    }
    
     public function orderhistoryAction(){
        }
     
      public function orderhistoryinnerAction(){
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
            $this->view->member = $meber =$defaultNamespace->user;
            $customer_id = $meber['CustomerNo'];
            $this->view->username = $Email = $meber['Email'];
            $order = new ShopOrder();
            $key = $order->getPrimaryKey();
            $where =' thistable.user_id = '.$customer_id . ' AND order_status !=0';
            $rowsorder = $order->getRecords($where,"$key DESC", null, 0);
           
            if (count($rowsorder) > 0) {
                    $this->view->roworder = $row = $rowsorder;
                }
            }
       }
       
       public function historystorecreditAction(){
        
        }
        
         public function historystorecreditinnerAction(){
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
            $this->view->member = $meber =$defaultNamespace->user;
            $customer_id = $meber['CustomerNo'];
            $this->view->username = $Email = $meber['Email'];
            $cusomer = new Customer();
            $key = $cusomer->getPrimaryKey();
            $where =' thistable.CustomerNo = '.$customer_id;
            $rowcusomer = $cusomer->getRecords($where,"$key DESC", null, 0);
           
            if (count($rowcusomer) > 0) {
                    $this->view->rowcusomer = $row = $rowcusomer;
                }
            }
        }
    
    public function listusernewAction(){
                       
            //$id = (int)$this->getParam("id");
            $user = new User();
            $key = $user->getPrimaryKey();
            $where ='node.status = 1';
            $rows = $user->getRecords($where,"$key DESC", 10);

            $this->view->users =$rows;
          
    }
    public function listusernewhomepageAction(){
                       
            //$id = (int)$this->getParam("id");
            $user = new User();
            $key = $user->getPrimaryKey();
            $where ='node.status = 1';
            $rows = $user->getRecords($where,"$key DESC", 10);

            $this->view->users =$rows;
          
    }
    public function  registerdetailAction(){
        $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
        $conf = Vnf::getConfigs('conf');
        @$registermail = $conf->registermail?$conf->registermail:'info@'.$domain;
        //city db
        //$city = new Zipcodes();
        //$city = new City();
        ////$rowcity = $city->getRecords(null, null, null, null, 'CITY', array('CITY'));
        //$rowcity = $city->fetchAll();
        //$this->view->rowcity = $rowcity;
        $country = new Country();
        $rowcountry = $country->fetchAll();
        $this->view->rowcountry = $rowcountry;


        if($this->_request->isPost()){
                $user = new Customer();
                $email = $this->getParam("email"," ");
                //$root = $user->getRoot();
                //$rootId = null;
                //@$rootId = $root->category_id;
                
                $firstname = $this->getParam("firstname","");
                $lastname = $this->getParam("lastname");
                $username =  $this->getParam("username");
                $address = $this->getParam("address");
                $address2 = $this->getParam("address2");
                $city = $this->getParam("city");
                $zipcode = $this->getParam("zipcode");
                $country = $this->getParam("country");
                $password = $this->getParam("password");
                $state = $this->getParam("state");
                //                $phone = $this->getParam("phone");
                //                $mobil = $this->getParam("mobil");
                $gender = $this->getParam("gender");
                $date = $this->getParam("birthday");
                $aboutme = $this->getParam("aboutme");
                $looking = $this->getParam("looking");
                $iam = $this->getParam("iam");
                $seeking = $this->getParam("seeking");
                $for = $this->getParam("for");
                $edu = $this->getParam("edu");
                $smoking = $this->getParam("smoking");
                $height = $this->getParam("height");
                $weight = $this->getParam("weight");
                $company = $this->getParam("company");
                //$mobilfone = $this->getParam("mobilfone");
                $numberfone = $this->getParam("numberfone");
                $fax = $this->getParam("fax");
                $about_us = $this->getParam("aboutus");


                        $this->view->email = $email;
                        $this->view->firstname = $firstname;
                        $this->view->lastname = $lastname;
                        $this->view->username = $username;
                        $this->view->address = $address;
                        $this->view->address2 = $address2;
                        $this->view->city = $city;
                        $this->view->zipcode = $zipcode;
                        $this->view->country = $country;
                        
                        $this->view->aboutme = $aboutme;
                        $this->view->looking = $looking;
                        
                        $this->view->iam = $iam;
                        $this->view->seeking = $seeking;
                        $this->view->for = $for;
                        $this->view->edu = $edu;
                        $this->view->smoking = $smoking;
                        $this->view->height = $height;
                        $this->view->weight = $weight;
                        $this->view->company = $company;
                        $this->view->state = $state;
                        //$this->view->mobilfone = $mobilfone;
                        $this->view->numberfone = $numberfone;
                        $this->view->fax = $fax;
                        $this->view->about_us = $about_us;
                        
                $defaultNamespace = new Zend_Session_Namespace('Default');
                if ( $this->getParam("captcha") != $defaultNamespace->security_code) {
                    if ('' != $this->getParam("captcha")) {
                        $this->view->error = $error = "Wrong Captcha!";
                    }
                    return;
                }
                
                if(" " != $email){
                    $where = 'email ="'.$email.'"';

                    $row = $user->fetchRow($where);
                    //echo username or email exists
                    if(count($row)>0){

                        $this->view->error = $error = "Email already exists";

                    }
                    else{

                        $birthday = date('Y-m-d', strtotime( $date ));
                        $registrydate = date('Y-m-d H:i:s',time());
                        $codeActive = time();
                        $data = array(
                            //'admin_title' => 'New member',
                            //'username' => time(),
                            
                            'LastName' => $lastname,
                            'FirstName' => $firstname ,
                            'Company'=>$company,
                            'Street' => $address,
                            'Street2' => $address2,
                            'City' => $city,
                            'Zip' => $zipcode ,
                            'Country' => $country ,
                            'State' => $state ,
                            //'Phone'=>$mobilfone,
                            'Phone2'=>$numberfone,
                            'Fax'=>$fax,
                            'Email' => $email,
                            'Password' => $password,
                            'activecode'=> $codeActive,
                            'status' => '1',
                            //'about_us' =>$about_us,

                            /*
                            'registrydate' => $registrydate,
                            'gender' => $gender ,
                            'iam'=> $iam,
                            'seeking'=> $seeking,
                            'for'=> $for,
                            'edu'=> $edu,
                            'smoking'=> $smoking,
                            'aboutme'=>$aboutme,
                            'looking'=>$looking,
                            'height'=>$height,
                            'weight'=>$weight,
                            */
                        );
                
                        $link = "http://" . $_SERVER['HTTP_HOST'] . BASE_URL ."/user/active?activecode=$codeActive";	//goi active de gui so random active status =1
                        $user->insert($data);
                        $mail = new Zend_Mail("utf-8");
                        //$mail->setBodyHtml("Click <a href='$link'>here</a> to active your account")
                        $mail->setBodyHtml("Thanks for register your account!")
                        ->setFrom($registermail)
                        ->addTo($email)
                        ->setSubject("Register successful");
                        
                        $mail->send();
                        $this->view->message = "<div style='padding: 10px; color:red; font-size:15px;'>Registration accepted.</div>";
                        //$this->_redirect("index");
                    }
                }


            }
    }
    
    public function  registerdetailoldAction(){
        $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
        $conf = Vnf::getConfigs('conf');
        @$registermail = $conf->registermail?$conf->registermail:'info@'.$domain;
        //city db
        //$city = new Zipcodes();
        //$city = new City();
        ////$rowcity = $city->getRecords(null, null, null, null, 'CITY', array('CITY'));
        //$rowcity = $city->fetchAll();
        //$this->view->rowcity = $rowcity;
        $this->view->rowcity = array();


        if($this->_request->isPost()){
                $user = new User();
                $email = $this->getParam("email"," ");
                $root = $user->getRoot();
                $rootId = null;
                @$rootId = $root->category_id;
                
                $firstname = $this->getParam("firstname","");
                $lastname = $this->getParam("lastname");
                $username =  $this->getParam("username");
                $address = $this->getParam("address");
                $city = $this->getParam("city");
                $zipcode = $this->getParam("zipcode");
                $country = $this->getParam("country");
                $password = $this->getParam("password");
                $state = $this->getParam("state");
                //                $phone = $this->getParam("phone");
                //                $mobil = $this->getParam("mobil");
                $gender = $this->getParam("gender");
                $date = $this->getParam("birthday");
                $aboutme = $this->getParam("aboutme");
                $looking = $this->getParam("looking");
                $iam = $this->getParam("iam");
                $seeking = $this->getParam("seeking");
                $for = $this->getParam("for");
                $edu = $this->getParam("edu");
                $smoking = $this->getParam("smoking");
                $height = $this->getParam("height");
                $weight = $this->getParam("weight");
                $company = $this->getParam("company");
                $mobilfone = $this->getParam("mobilfone");
                $numberfone = $this->getParam("numberfone");
                $fax = $this->getParam("fax");
                 $about_us = $this->getParam("aboutus");

                        $this->view->email = $email;
                        $this->view->firstname = $firstname;
                        $this->view->lastname = $lastname;
                        $this->view->username = $username;
                        $this->view->address = $address;
                        $this->view->city = $city;
                        $this->view->zipcode = $zipcode;
                        $this->view->country = $country;
                        
                        $this->view->aboutme = $aboutme;
                        $this->view->looking = $looking;
                        
                        $this->view->iam = $iam;
                        $this->view->seeking = $seeking;
                        $this->view->for = $for;
                        $this->view->edu = $edu;
                        $this->view->smoking = $smoking;
                        $this->view->height = $height;
                        $this->view->weight = $weight;
                        $this->view->company = $company;
                        $this->view->state = $state;
                        $this->view->mobilfone = $mobilfone;
                        $this->view->numberfone = $numberfone;
                        $this->view->fax = $fax;
                        $this->view->about_us = $about_us;
                        
                $defaultNamespace = new Zend_Session_Namespace('Default');
                if ($this->getParam("captcha") != $defaultNamespace->security_code) {
                    $this->view->error = $error = "Wrong Captcha!";
                    return;
                }
                
                if(" " != $email){
                    $where = 'email ="'.$email.'" or username = "'.$username.'"';

                    $row = $user->fetchRow($where);
                    //echo username or email exists
                    if(count($row)>0){

                        $this->view->error = $error = "Email or Username already exists";

                    }
                    else{

                        $birthday = date('Y-m-d', strtotime( $date ));
                        $registrydate = date('Y-m-d H:i:s',time());
                        $codeActive = time();
                        $data = array(
                            'admin_title' => 'New member',
                            'username' => time(),
                            'password' => $password,
                            'firstname' => $firstname ,
                            'lastname' => $lastname,
                            'email' => $email,
                            'address' => $address,
                            'city' => $city,
                            'zipcode' => $zipcode ,
                            'country' => $country ,
                            'state' => $state ,
                            'registrydate' => $registrydate,
                            'gender' => $gender ,
                            
                            'status' => '0',
                            'activecode'=> $codeActive,
                            
                            'iam'=> $iam,
                            'seeking'=> $seeking,
                            'for'=> $for,
                            'edu'=> $edu,
                            'smoking'=> $smoking,
                            'aboutme'=>$aboutme,
                            'looking'=>$looking,
                            'height'=>$height,
                            'weight'=>$weight,
                            
                            'company'=>$company,
                            'mobilfone'=>$mobilfone,
                            'numberfone'=>$numberfone,
                            'fax'=>$fax,
                        );
                
                        $link = "http://" . $_SERVER['HTTP_HOST'] . BASE_URL ."/user/active?activecode=$codeActive";	//goi active de gui so random active status =1
                        $user->insert($data);
                        $mail = new Zend_Mail("utf-8");
                        $mail->setBodyHtml("Click <a href='$link'>here</a> to active your account")
                        ->setFrom($registermail)
                        ->addTo($email)
                        ->setSubject("Register successful");
                        
                        $mail->send();
                        
                        $this->_redirect("user/active");
                    }
                }


            }
    }
    public function changepasswordinnerAction(){
        $this->processLoginAction();

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $userLogged = $defaultNamespace->user;
        if ($defaultNamespace->access) {
            $id = $userLogged['CustomerNo'] ;

            $pass = $this->getParam("passold", '');
            $passnew = $this->getParam("passnew", '');
            $loginForm = $this->getParam("loginform", 0);
            if('' != $pass && !$loginForm){
                //$id =(int)$this->getParam("id");
                $user = new Customer();
                $where = 'CustomerNo = "'.$id.'" and password ="'.$pass.'"';
                $row = $user->fetchRow($where);
                
                if(count($row)>0){
                    
                    $whereid = 'CustomerNo = '.$id;
                    $data = array(
                        'password' => $passnew
                    );
                    $user->update($data, $whereid);
                    //$this->view->error = $error ="Password Changed";
                    $userOb = new Customer();
                    $result = $userOb->getRecords("CustomerNo = '" . $userLogged['CustomerNo'] . "'");
                    if (count($result) > 0)
                    {
                    $defaultNamespace = new Zend_Session_Namespace('Default');
                    $defaultNamespace->user = $result[0];
                    }

                    $this->view->error = $error ="Change Password Successfull";
                    
                }
                else{
                    $this->view->error = $error ="Wrong Password";
                }
            }
        }
    }
    public function changepasswordAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        $currentPage = $this->view->currentPage;
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
    }

    public function viewprofileAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }

    public function viewprofileinnerAction(){
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $country = new Country();
        $rowcountry = $country->fetchAll();
        $this->view->rowcountry = $rowcountry;

        if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
             $this->view->member = $meber =$defaultNamespace->user;
            $customer_id = $meber['CustomerNo'];
            $user = new Customer();
            //print_r($row);die;
            $where = "this";
            $user = $user->getRecords("thistable.CustomerNo = '$customer_id'", null, 1 ,0);
            if (count($user) > 0) {
                $this->view->row = $user[0];
            }
            //print_r($this->view->row);die;
        }
    }
    

    public function uploadimageinnerAction(){
        $result = array();
        $currentPage = $this->view->currentPage;
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $row = $defaultNamespace->user;
        $loginform = $this->getParam("loginform", 0);
        if($this->_request->isPost()){
         try {
                $fieldUpload = 'upload';
                $newImageName = '';
                try {
                    $uploadPath = UPLOAD_PATH . "/" . $this->_request->getControllerName();
                    if(Zend_Upload::isFileUpload($fieldUpload)) {
                    //echo "fffkkkk";
                        if(!is_dir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath))
                        mkdir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777, true);
                        chmod($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);

                        $newImageName = time(). '_' . rand();
                        $objImageUpload = new Zend_Upload($fieldUpload, $_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath);
                        $objImageUpload->setName($newImageName);
                        $objImageUpload->upload();
                        $saveImgName = $newImageName . "." .$objImageUpload->getFileExtention();
                        $newImageName = $uploadPath . "/" . $newImageName . "." .$objImageUpload->getFileExtention();
                    }
                    //$data[$fieldUpload] = $newImageName;
                } catch (Zend_Upload_Exception $ex){
                    $result['success'] = false;
                    //$result['message'] = $this->view->translate->_("Error on upload.") . "<br>" . $ex->getMessage();
                }
               //echo  $row['category_id'];die;
                $data =array(
                    'category_id' => $row['category_id'],
                    'image_path' => $newImageName


                );
                
                $image = new Image();
                //echo "category_id = {$row['category_id']}";
                $image_exists = $image->fetchRow("category_id = {$row['category_id']}");
                
                $image->insert($data);
                
                if (count($image_exists) == 0) {
                    print_r($image_exists);
                    $user = new User();
                    $data =array(
                        'main_image' => $newImageName
                    );
                    $user->update($data, "category_id = {$row['category_id']}");
                }
                
                $result['success'] = true;
                $result['message'] = $this->view->translate->_("Insert successfull.");
                $this->view->message = $result['message'];
            } catch(Exception $ex) {
                $result['message'] = $this->view->translate->_("Can't insert to DB") . "<br>" . $ex->getMessage();
            }
        }
    }
    public function uploadimageAction(){
         $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
    }
    public function listimageinnerAction(){
        $currentPage = $this->view->currentPage;
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $this->view->user = $user = $defaultNamespace->user;
        $loginform = $this->getParam("loginform", 0);
        $image = new Image();
        $where = 'category_id ='.(int)$user['category_id'];
        $rows = $image->getRecords($where, 'image_id Desc');
        $this->view->rows = $rows ;
        

    }
    public function listimageAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        $currentPage = $this->view->currentPage;

        
    }
    public function deleteimageAction(){
        $id= (int)$this->getParam('id',0);
        if($id > 0){
            $image = new Image();
            $where = 'image_id='.$id;
            $image->delete($where);
            $this->_redirect('user/listimage');
        }
    }
    
    public function imagesinnerAction(){
        $currentPage = $this->view->currentPage;
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        
        //$defaultNamespace = new Zend_Session_Namespace('Default');
        //$user = $defaultNamespace->user;
        //$loginform = $this->getParam("loginform", 0);
        
        $image = new Image();
        
        $id = (int)$this->getParam('id', 0);
        if ($id > 0) {
            $where = 'category_id =' . $id;
            
            $rows = $image->getRecords($where, 'image_id Desc');
            
            $this->view->rows = $rows ;
        }
        

    }
    public function imagesAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function calendarfreetimeAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    public function calendarfreetimeinnerAction() {
    
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $row = $defaultNamespace->user;
        
        if ($defaultNamespace->access) { // logged
            $day = (int)$this->_getParam("month", (int)date('d', time()));
            $month = (int)$this->_getParam("month", (int)date('m', time()));
            $year = (int)$this->_getParam("year", (int)date('Y', time()));

            if($month <= 0 || $month > 12) {
               $date = time();
               $month = (int)date('m', $date);
               $year = (int)date('Y', $date);
            }

            //echo "$month/$day/$year";
            $date = strtotime("$month/01/$year");

            $curentMonth = ((int)date('m', time()) == $month) && ((int)date('Y', time()) == $year);

            $this->view->current_day = (int)date('d', time());
            $this->view->same_month_year = $curentMonth;
            $this->view->month = $month;
            $this->view->month_show = date("F",$date);
            $this->view->year = $year;
            $this->view->count_days = date('t', $date);
            $this->view->day_of_week = (int)date('w', $date);
            /**
             * get pre and next month/year
             *
             */

            $preMonth = $month - 1;
            $nextMonth = $month + 1;
            $preYear = $year;
            $nextYear = $year;
            if ($preMonth <= 0) {
                $preMonth = 12;
                $preYear--;
            }

            if ($nextMonth > 12) {
                $nextMonth = 1;
                $nextYear++;
            }

            $this->view->preMonthView = date('F', strtotime("$preMonth/01/$preMonth"));
            $this->view->nextMonthView = date('F', strtotime("$nextMonth/01/$nextYear"));

            $this->view->preMonth = $preMonth;
            $this->view->nextMonth = $nextMonth;
            $this->view->preYear = $preYear;
            $this->view->nextYear = $nextYear;
            
            $objEvent = new FreeTime();
            $where = "1";
            //$order = array($arr_sort[$sortby] . " " . $arr_order[$orderby]);
            //$order = "EventDate ASC";
            
            $where .= " AND Month(from_time) = '$month' AND YEAR(from_time) = '$year' AND user_id = '{$row['category_id']}'";
                
            
            $arrData = $objEvent->fetchAll($where);
            
            //print_r($arrData->toArray());die;
            
            $events = array();
            if(count($arrData) > 0) {
                foreach ($arrData as $data) {
                    $day = (int)(date('d', strtotime($data->from_time)));
                    $events[$day][] = $data;
                }
            }
            $this->view->events = $events;


            
            $yearOption = array();
            $yearF = date('Y')+1;
            $yearP = '2007';
            for ( $i=$yearF; $i>=$yearP; $i-- ){
                $yearOption[$i] = $i;
            }
            $this->view->yearOption = $yearOption;

            $monthOption = array();
            for($i = 1; $i < 13 ; $i++) {
                $monthOption[$i] = date('M', strtotime("$i/01/2009"));
            }
            $this->view->monthOption = $monthOption;
        }
    }
    
    public function addfreetimeAction(){
         $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
    }
    
    public function addfreetimeinnerAction(){
        $currentPage = $this->view->currentPage;

        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $row = $defaultNamespace->user;

        $loginform = $this->getParam("loginform", 0);
        $user = new User();
        $this->view->user =$row;
        $fromtime = $this->getParam('from');
        if('' != $fromtime){
            
            $date = $this->getParam('date', '');
            
            $freetime = new FreeTime();
            
            $fromtime = "$date $fromtime";
            $totime = $this->getParam('to');
            $totime = "$date $totime";
            
            //echo $fromtime;die;
            $data = array(
                'user_id' => $row['category_id'],
                'from_time' => $fromtime,
                'to_time' => $totime
            );
            $id = (int)$this->getParam('id', 0);
            if($id > 0) {
                $freetime->update($data, "free_time_id = '$id'");
            } else {
                $freetime->insert($data);
            }
            
            $this->view->error = $error ="Add Free Time Successfull";
        }
        $this->_redirect('/user/calendarfreetime');
    }
    function updatelevelinnerAction(){
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $currentPage = $this->view->currentPage;
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $loginform = $this->getParam("loginform", 0);
        $usersesion = $defaultNamespace->user;
        $id = $usersesion['category_id'];
        $level = new Level();
        $level_pk = $level->getPrimaryKey();
        
        $rowlevel = $level->fetchAll(null, "$level_pk ASC");
        $this->view->levelrow = $rowlevel;
        
        $user1 = new User();
        $current = $user1->fetchRow('category_id ='.$id);
        $currentid = 'level_id ='.$current['level_id'];
         //echo $currentid;die;
        $currentname = $level->fetchRow($currentid);
        
        $this->view->currentlevel = $currentname['level_name'];
        
        $country = new Country();
        $rowcountry = $country->fetchAll();
        $this->view->rowcountry = $rowcountry;

               //$id = (int)$this->getParam('id','');
        
        $firstname = $this->getParam('firstname','');
        $level = (int)$this->getParam('level','');
        
        if('' != $firstname){
            $user = new User();
            $level1 = new Level();
            //echo '000000'.$level;die;
            $where = 'category_id='.$id;
            $rowold = $user->fetchRow($where);
            $levelold = 'level_id ='.$rowold['level_id'];

            $current_date = date('Y-m-d H:i:s');
            $oldday = is_null($rowold['expiration_date'])?$current_date:$rowold['expiration_date'];

            if ($oldday < $current_date) {
                $oldday = $current_date;
            }

            $leveloldname = $level1->fetchRow($levelold);//name old level
            $levelnewname = $level1->fetchRow('level_id ='.$level);//new old level
            if($leveloldname['level_name'] == $levelnewname['level_name'] ){
               $note = 'charge for  '.$leveloldname['level_name'] . " (" . $levelnewname['num_days_expire'] . "days)";
            }  else {
                $note = 'update: '.$leveloldname['level_name'].' to '.$levelnewname['level_name'] . " (" . $levelnewname['num_days_expire'] . "days)";
            }
            $price = $levelnewname['price'];
            $lastname = $this->getParam('lastname');
            $address = $this->getParam('address', '');
            $city = $this->getParam('city', '');
            $state = $this->getParam('state', '');
            $zipcode= $this->getParam('zipcode', '');
            $phone = $this->getParam('phone', '');
            $country = $this->getParam('country', '');
            $email = $this->getParam('email', '');
            $card =  $this->getParam('credit_card');
            
            $card_type =  $this->getParam('card_type');
            $expiration_date =  $this->getParam('expiration_date');
            $cvv =  $this->getParam('cvv');
            
            $history = new History();
            $datahis =array(
               'user_id' => $id,
               'firstname' => $firstname,
               'lastname' => $lastname,
               'address' => $address,
               'city' => $city,
               'zipcode' => $zipcode,
               'state' => $state,
               'phone' => $phone,
               'email' => $email,
               'country' => $country,
               'credit_card'=>$card,
               'price' => $price,
               'note' => $note,
               'card_type' => $card_type,
               'expiration_date' => $expiration_date,
               'cvv' => $cvv,
            );
            $history->insert($datahis);
            
            //add_date($givendate, $day=0, $mth=0, $yr=0, $format = 'Y-m-d h:i:s')
            $newday = $this->add_date($oldday,0, (int)$leveloldname['num_days_expire']);
            
            //$newday = $this->add_date(;
            //echo $newday;die;
            $data =array(
               'level_id' => $level,
               'expiration_date' => $newday
            );
            $user->update($data, $where);
            $this->_redirect('user/listhistory');
            //echo 'Update Successful Click <a href="">Back</a>';
        }
    }
    function updatelevelAction(){
        
       $this->setLayout(DEFAULT_LAYOUT);
         $this->prepareData();
    }
    function listhistoryAction(){
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    function listhistoryinnerAction(){
         $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $currentPage = $this->view->currentPage;
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');

        $loginform = $this->getParam("loginform", 0);
        $usersesion = $defaultNamespace->user;
         $history = new History();
         $where = 'user_id='.$usersesion['category_id'];
         //echo $usersesion['category_id'];die;

         $rows = $history->getRecords($where,'time desc');
         $this->view->rows =$rows;
    }
    
    public function getcityAction() {
        $state = $this->getParam('state', null);
        
        $where = null;
        if ($state) {
            $where = "STATE = '$state'";
        }
        $obj = new Zipcodes();
        $rowcity = $obj->getRecords($where, null, null, null, array('CITY'), 'CITY');
        $this->view->rowcity = $rowcity;
    }
    
    public function getzipcodeAction() {
        $city = $this->getParam('city', null);
        
        $where = null;
        if ($city) {
            $where = "CITY = '$city'";
        }
        $obj = new Zipcodes();
        $rowcity = $obj->getRecords($where, null, null, null, array('ZIP'), 'ZIP');
        $this->view->rowcity = $rowcity;
    }
    
    public function getcitymeetingAction() {
        $state = $this->getParam('state', null);
        
        $where = null;
        if ($state) {
            $where = "STATE = '$state'";
        }
        $obj = new Zipcodes();
        $rowcity = $obj->getRecords($where, null, null, null, array('CITY'), 'CITY');
        $this->view->rowcity = $rowcity;
    }
    
    public function getrestaurantAction() {
        $city = $this->getParam('city', null);
        $zip = $this->getParam('zip', null);
        
        $where = null;
        
        if ($city) {
            $where = "city = '$city'";
        }
        if ($zip) {
            if ($where) {
                $where .= " OR zip = '$zip'";
            } else {
                $where = "zip = '$zip'";
            }
        }
        
        $order = "name ASC";
        $obj = new Restaurant();
        $allRestaurant = $obj->getRecords($where, $order);
        $this->view->allRestaurant = $allRestaurant;
    }
    
    public function getcafeAction() {
        $city = $this->getParam('city', null);
        $zip = $this->getParam('zip', null);
        
        $where = null;
        
        if ($city) {
            $where = "city = '$city'";
        }
        /*
        if ($zip) {
            if ($where) {
                $where .= " OR zip = '$zip'";
            } else {
                $where = "zip = '$zip'";
            }
        }
        */
        
        $order = "location ASC";
        $obj = new Starbucks();
        $allStarbucks = $obj->getRecords($where, $order);
        $this->view->allStarbucks = $allStarbucks;
    }
    
    function add_date($givendate, $day=0, $mth=0, $yr=0, $format = 'Y-m-d h:i:s') {
        $cd = strtotime($givendate); // get current date
        
        $newdate = date($format, mktime(date('h',$cd),
            date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
            date('d',$cd)+$day, date('Y',$cd)+$yr)
        );
        return $newdate;
    }
    
    public function setavatarAction() {
        $this->processLoginAction();
        
        $id = $this->getParam('id', 0);
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        
        if ($id > 0 && $defaultNamespace->access) {
            $image = new Image();
            //echo "category_id = {$row['category_id']}";
            $image_exists = $image->fetchRow("image_id = '$id'");
            $newImageName = $image_exists['image_path'];
            
            $user = $defaultNamespace->user;
            @$user_id = $user['category_id'];
            
            $user = new User();
            $data =array(
                'main_image' => $newImageName
            );
            $user->update($data, "category_id = '$user_id'");
            
            // update session
            $defaultNamespace = new Zend_Session_Namespace('Default');                
            $user = $defaultNamespace->user;
            
            $user['main_image'] = $newImageName;
            $defaultNamespace->user = $user;
            
            echo "Avatar has been set to your account";
        } else {
            echo "Avatar can't set to your account";
        }
        die;
    }
    
    public function changecolorAction() {
    
        $color = $this->getParam('color', null);
        
        if (null != $color) {
            echo $myFile = BASE_DIR . "/src/net/vietnamfriendly/public/css/bgcolor.css";
            $fh = fopen($myFile, 'w') or die("can't open file");
            $stringData = "body{background:#$color}";
            fwrite($fh, $stringData);
            fclose($fh);
            
        }
        die;
    }
    public function captchaAction()
    {
        //Let's generate a totally random string using md5
        $md5_hash = md5(rand(0,999));
        //We don't need a 32 character long string so we trim it down to 5
        $security_code = substr($md5_hash, 15, 5); 

        //Set the session to store the security code
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultNamespace->security_code = $security_code;

        //Set the image width and height
        $width = 100;
        $height = 22;  

        //Create the image resource
        $image = ImageCreate($width, $height);  

        //We are making three colors, white, black and gray
        $white = ImageColorAllocate($image, 255, 255, 255);
        $black = ImageColorAllocate($image, 0, 0, 0);
        $grey = ImageColorAllocate($image, 204, 204, 204); 

        //Make the background black
        ImageFill($image, 0, 0, $white); 

        //Add randomly generated string in white to the image
        ImageString($image, 5, 30, 3, $security_code, $black); 

        //Throw in some lines to make it a little bit harder for any bots to break
        ImageRectangle($image,0,0,$width-1,$height-1,$grey);
        //imageline($image, 0, $height/2, $width, $height/2, $grey);
        //imageline($image, $width/2, 0, $width/2, $height, $grey);
        //imageline($image, 0, 0, $width, $height, $grey);
        //imageline($image, $width, 0, 0, $height, $grey); 

        //Tell the browser what kind of file is come in
        header("Content-Type: image/jpeg"); 

        //Output the newly created image in jpeg format
        ImageJpeg($image); 

        //Free up resources
        ImageDestroy($image);
    }
    
    public function otherfreetimeinnerAction() {
        $this->view->date = $date = $this->getParam('date');
        
        $freetime = new FreeTime();
        if ($date !="") {
            $fromtime = date('Y-m-d\T00:00:00', strtotime( $date ));
            $totime = date('Y-m-d\T23:59:59',  strtotime($date));
            $where = 'from_time between "'.$fromtime.'" and "'.$totime.'"';//dk lay nhung record trong ngay
        } else {
            $fromtime = date('Y-m-d\T00:00:00', ( time()));
            $where = 'from_time >= "'.$fromtime.'"';//dk lay nhung record trong ngay
        }
        
        
        $allItems = $freetime->getRecords($where, 'from_time ASC');
        $this->view->allItems = $allItems;
    }
    public function otherfreetimeAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function activeinnerAction() {
        $currentPage = $this->view->currentPage;

        $active = $this->getParam('activecode', '');
        if('' != $active){

            $user =new Customer();
            $where = "activecode ='".$active."'";
            $row = $user->fetchRow($where);
                        
            if($row){
                //$row= $row->toArray();
                $data = array(
                    'status' => 1
                );
                $whereid = 'category_id= '.$row->category_id;
                $user->update($data,$whereid);
                $this->view->activecode = 1;
                //$this->_redirect("user/active");
            } else {
                echo "code active ko dung";
            }
        }
    }
    
    public function invoiceAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function invoiceinnerAction() {
        $this->view->id = $id = $this->getParam('id', 0);
        
        if($id > 0) {
            $where = "order_id = '$id'";
            
            $objOrder  = new ShopOrder();
            $this->view->order = $order = $objOrder->fetchRow($where);
            
            
            $obj = new ShopOrderItem();
            
            $where = "OrderID = '$id'";
            $pk = $obj->getPrimaryKey();
            $this->view->invoice = $obj->getRecords($where);
        }
    }
    public function checkgiftcardAction() {

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $gcno = $this->getParam('gcno', '');
        
        if ($gcno != '') {
            $giftcard = new Giftcard();
            
            $where = "GiftCardNo = '$gcno' AND ActiveYN=1";
            $card = $giftcard->fetchRow($where);
            
            if ($card) {
                if ($card->Amount > 0) {
                    $cardAmount = $card->Amount;
                    $defaultNamespace->cartTotal;
                    $maxAmount = $cardAmount>=$defaultNamespace->cartTotal?$defaultNamespace->cartTotal:$cardAmount;
                    
                    //$defaultNamespace->cartTotal -= $maxAmount;
                    
                    //$defaultNamespace->coupon = null;
                    $defaultNamespace->giftCard = $gcno;
                    $defaultNamespace->giftCardPrice = $maxAmount;
                    
                    echo Zend_Json::encode(array("msg" => "Value: \$" . $card->Amount, "success" => true));die;
                } else {
                    echo Zend_Json::encode(array("msg" => "Your gift card is empty", "success" => false));
                    die;
                }
            } else {
                //echo Zend_Json::encode(array("msg" => "Gift card has been updated.", "success" => true, 'giftcardupdate' => $maxAmount, 'cartTotal' => $defaultNamespace->cartTotal - $maxAmount));die;
            }
        }
        echo Zend_Json::encode(array("msg" => "Can not use your gift card.", "success" => false));
        die;
    }
}